import {defineStore} from "pinia";
import {ref} from "vue";
import {conUtils} from "../../utils/conUtils";
import {getWxShare, openService, toMiniAppBusiness} from "../../utils/utils";
import {jssdk} from "../../services";
// #ifdef H5
import jweixin from 'weixin-js-sdk'
// #endif
import {useUserInfoStore} from "./userInfo";

export const useCommonInfoStore = defineStore("CommonInfo", () => {
        const officialAccountInfo = ref()
        const serviceUrl = ref()
        const reward = ref()
        const systemInfos = ref()
        const parentId = ref()// 应用分享父级ID
        const invite_link_id = ref(1) // 外部平台分享ID
        const resellerId = ref()
        const address = ref()
        const addressDel = ref()
        const isNoShow = ref(false) // 不在显示复制提示
        const isShowRed = ref(false)
        const time = ref()
        const notice_create_time = ref()
        const applet_sh = ref(false)
        const source = ref('') //渠道来源
        const jsdkConfig = ref()
        const callback = ref() //广告平台回调callback
        const useUser = useUserInfoStore() // 使用userInfoStore状态管理器
        const setNoticeCreateTime = (value) =>{
            notice_create_time.value = value
        }
        const setJSDKConfig = async () => {
            const res = await jssdk()
            jsdkConfig.value = res.result
        }
        // wx api 注册
        const initJSDKConfig = async (isShare = false) => {
            if (!jsdkConfig.value) {
                await setJSDKConfig()
            }
            jweixin.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: jsdkConfig.value.appId, // 必填，公众号的唯一标识，填自己的！
                timestamp: jsdkConfig.value.timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
                nonceStr: jsdkConfig.value.nonceStr, // 必填，生成签名的随机串
                signature: jsdkConfig.value.signature, // 必填，签名，见附录1
                jsApiList: jsdkConfig.value.jsApiList, // 必填，如果只是为了跳转小程序，随便填个值都行
                openTagList: ["wx-open-launch-weapp",'updateAppMessageShareData', 'updateTimelineShareData'] // 跳转小程序时必填
            });
            console.log("getConfig", jsdkConfig)
            jweixin.ready((e) => {
                console.log('成功验证', e)
            })
            jweixin.error((e) => {
                console.log('失败信息', e)
            })
            if (!isShare) {
                return jweixin
            }
        }

        //检测红包弹窗9-24小时一次
        const getShowRed = () => {
            // time.value = '' //测试用，时间重置为空，记得注释
            // 弹窗24小时一次
            /* if (!time.value || new Date().getHours() - time.value > 1000 * 60 * 60 * 24) {
                time.value = new Date().getTime()
                isShowRed.value = true
            } else {
                isShowRed.value = false
            } */
            // 获取当前小时
            let hours = new Date().getHours()
            // 弹窗9-24小时一次
            if (hours >= 9 && hours < 24){
                // 获取弹窗是否弹过
                let ispopShow = uni.getStorageSync('ispopShow')
                if (!ispopShow) {
                    isShowRed.value = true
                } else {
                    isShowRed.value = false
                }
                return isShowRed.value
            } else if (hours < 9) {
                isShowRed.value = false
                // 存储弹窗是否弹过-false
                uni.setStorageSync('ispopShow', false)
                return isShowRed.value
                //返回上一次弹窗的时间催
                return time.value
            }
        }
        // 自定义24小时执行一次事件
        const getShowExecuteEvent = (e) => {
            // 获取最后一次计时的时间
            const lastTime = uni.getStorageSync('lastRecordTime');
            let isNewTime = uni.getStorageSync('isRecordTime')
            // 当前时间
            let currentTime = new Date().getTime();
            // 24小时的毫秒数
            const oneDay = 24 * 60 * 60 * 1000;
            if (!lastTime || (currentTime - lastTime) > oneDay) {
                // 如果本地存储中没有记录或者已超过24小时，则显示弹窗
                uni.setStorageSync('lastRecordTime', currentTime); // 更新本地存储的时间
                uni.setStorageSync('isRecordTime', true); // 更新本地存储的时间布尔值
                return true
            } else {
                isNewTime = e
                // 如果未超过24小时，则不显示弹窗
                if (isNewTime === false){
                    console.log('老用户', isNewTime);
                    uni.setStorageSync('isRecordTime', false);
                    return false
                }else if (isNewTime === true) {
                    console.log('新用户', isNewTime);
                    uni.setStorageSync('isRecordTime', true);
                    return true
                }else {
                    console.log('无记录', isNewTime);
                    return uni.getStorageSync('isRecordTime');
                }
            }
        }
        const setAddress = (addressVal) => {
            address.value = addressVal
            conUtils("addressVal", addressVal)
        }
        const setAddressDel = (addressVal) => {
            addressDel.value = addressVal
            conUtils("addressVal", addressVal)
        }
        const setIsNoShow = (isNoShowVal) => {
            isNoShow.value = isNoShowVal
            conUtils("isNoShowVal", isNoShowVal)
        }
        // 设置应用分享父级ID
        const setParentUid = (parentIdVal) => {
            parentId.value = parentIdVal
            conUtils("parentIdVal", parentIdVal)
        }
        // 设置外部平台分享ID
        const setInviteLinkId = (InviteLinkIdVal) => {
            invite_link_id.value = InviteLinkIdVal
        }
        const setSource = (sourceVal) => {
            source.value = sourceVal
            conUtils("sourceVal", sourceVal)
        }

        const clearId = () => {
            parentId.value = undefined
            resellerId.value = undefined
            isNoShow.value = false
        }

        const setParentRid = (resellerIdVal) => {
            resellerId.value = resellerIdVal
            conUtils("resellerIdVal", resellerIdVal)
        }

        const setInfo1 = (officialAccountInfoVal) => {
            officialAccountInfo.value = officialAccountInfoVal
            conUtils("officialAccountInfoVal", officialAccountInfoVal)
        }

        const setInfo2 = (serviceUrlVal) => {
            serviceUrl.value = serviceUrlVal
            conUtils("serviceUrlVal", serviceUrlVal)
        }

        const setInfo3 = (rewardVal) => {
            reward.value = rewardVal
            conUtils("rewardVal", rewardVal)
        }
        const setSystemInfos = (systemInfoVal) => {
            systemInfos.value = systemInfoVal
            conUtils("systemInfoVal", systemInfoVal)
        }

        // 跳转客服
        const toKeFu = () => {
            openService()
        }
        const setApplet_version = (version) => {
            applet_sh.value = version === "1.3.6"
        }

        const setCallback = (callbackVal) => {
            callback.value = callbackVal
            conUtils("callbackVal", callbackVal)
        }


        const toPage = async (type, path) => {
            const id = type === 1 ? 'wx2c348cf579062e56' : 'wxece3a9a4c82f58c9';
            console.log('店铺类型', id)
            // await uni.navigateToMiniProgram({
            //     appId: id,
            //     path: path,
            // })
            await toMiniAppBusiness(type, path)
        }
        const setWxShare = (type = "message", money, userID, path = "/pages/index/index?parent_id=" + userID) => {
            return getWxShare({
                title: money && money > 0 ? '用领食,我总共节省了' + money + '元,快来看看你的吧' : '点外卖用领食周边购，每餐只要0-5元',
                path: path,
                type,
            });
        }
        const setWxShareMessage = (type = "message", message = "点外卖用领食周边购，每餐只要0-5元", userID, path = "/pages/index/index?parent_id=" + userID + "&source=2", imgUrl = "https://lsz.lszbg.com/imgs/share/share_bg.png", source='3') => {
            console.log("setWxShareMessage-->path", source)
            return getWxShare({
                title: message,
                path: path,
                source: source,
                type,
            }, imgUrl);
        }
        // 获取定位
        const getUserLocation = (getLocation, chooseLocation) => {
            wx.getSetting({
                success(res0) {
                    console.log('查看是否吊起过授权', res0)
                    console.log('查看是否吊起过授权000000000000', Object.keys(res0.authSetting).includes('scope.userLocation'))
                    // 查看是否吊起过授权
                    if (!Object.keys(res0.authSetting).includes('scope.userLocation')) {
                        getLocation()
                        return

                    }
                    console.log('查看是否吊起过授权111111111', res0.authSetting['scope.userLocation'])
                    // 已经吊起过授权并且拒绝授权
                    if (!res0.authSetting['scope.userLocation']) {
                        uni.showModal({
                            title: '您未开启地理位置授权',
                            content: '为了给您提供更好的服务，请您授权地理位置，谢谢',
                            success: res2 => {
                                if (res2.confirm) {
                                    wx.openSetting({
                                        success(res3) {
                                            console.log('吊起过授权---并且拒绝--重新设置授权', res3)
                                            // 成功授权地理位置
                                            if (res3.authSetting['scope.userLocation']) {
                                                getLocation()
                                            } else {
                                                // 未授权地理位置，默认显示贵阳
                                                console.log('重新授权---未允许，默认显示贵阳')
                                            }
                                        }
                                    })
                                } else {
                                    console.log('拒绝授权地理位置，默认显示贵阳')
                                }
                            }
                        })
                    } else {
                        getLocation()
                    }
                }
            })
            // uni.getSetting({
            //   success(res) {
            //     console.log("getLocation", res)
            //     console.log("getLocation", res.authSetting['scope.userLocation'])
            //     if (res.authSetting['scope.userLocation'] === undefined) {
            //       console.log("getLocation--->", undefined)
            //       getLocation()
            //       // uni.showModal({
            //       //   title: '温馨提示',
            //       //   content: '为了更好的为您提供附近店铺的位置，需要您同意开启《定位权限》',
            //       //   cancelText: "取消",
            //       //   confirmText: "开启权限",
            //       //   success(request) {
            //       //     if (request.confirm) {
            //       //
            //       //     }
            //       //   }
            //       // })
            //     } else if (res.authSetting['scope.userLocation'] === false) {
            //       console.log("getLocation--->", false)
            //       uni.showModal({
            //         title: '温馨提示',
            //         content: '抱歉您已拒绝《定位权限》，无法为您提供附近店铺位置，请手动定位',
            //         cancelText: "取消",
            //         confirmText: "手动定位",
            //         success(request) {
            //           if (request.confirm) {
            //             chooseLocation()
            //           }
            //         }
            //       })
            //     } else {
            //       console.log("getLocation--->", true)
            //       getLocation()
            //     }
            //   }
            // });
        }
        // 参数1：小数值，参数2：小数点后保留的位数，小数值后面多的0会被去掉，如：0.10，
        const twoFixed = (num, floatNum) => {
            if (floatNum){
                return Number(num).toFixed(floatNum).replace(/\.?0+$/, '')
            }else{
                return Number(num).toString()
            }
            // .replace(/(\.\d*?)0+$/, '$1')
            // return Number(num).toFixed(2).replace(/\.00$/, '')
        }
        return {
            officialAccountInfo,
            serviceUrl,
            reward,
            systemInfos,
            parentId, // 应用分享父级ID
            invite_link_id, // 外部平台分享ID
            source,
            callback,
            resellerId,
            address,
            isNoShow,
            time,
            notice_create_time,
            addressDel,
            applet_sh,
            setInfo1,
            setInfo2,
            setInfo3,
            setSystemInfos,
            setParentUid, // 应用分享父级ID
            setInviteLinkId, // 外部平台分享ID
            setSource,
            setParentRid,
            toKeFu,
            getUserLocation,
            setAddress,
            clearId,
            setIsNoShow,
            getShowRed,
            getShowExecuteEvent,
            toPage,
            setWxShare,
            setWxShareMessage,
            initJSDKConfig,
            setAddressDel,
            setNoticeCreateTime,
            setApplet_version,
            setCallback,
            twoFixed, // 保留两位小数
        }
    },
    {
        // 配置持久化
        persist: {
            // 调整为兼容多端的API
            storage: {
                setItem(key, value) {
                    uni.setStorageSync(key, value)
                },
                getItem(key) {
                    return uni.getStorageSync(key)
                },
            },
        },
    },
)
